package common

import (
	"bytes"
	"fmt"
	"gitee.com/goddesszz/gocommon/myutil"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"strings"
)

// DingTalkMessage 定义钉钉消息结构体
type DingTalkMessage struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
}

// SendDingTalk 发送钉钉消息
// message 文本消息
// tag 消息标签，取值为：error、warn
func SendDingTalk(message string, tag string) {
	tag = fmt.Sprintf("[%s]-", strings.ToUpper(tag))
	token := os.Getenv("DINGTALK_TOKEN")
	if token == "" {
		logrus.Errorf("DINGTALK_TOKEN 缺失")
		return
	}
	dingTalkMessage := DingTalkMessage{
		MsgType: "text",
		Text: struct {
			Content string `json:"content"`
		}{
			Content: tag + message,
		},
	}

	jsonData := myutil.JsonToString(dingTalkMessage)

	webhookURL := fmt.Sprintf("https://oapi.dingtalk.com/robot/send?access_token=%s", token)

	resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer([]byte(jsonData)))
	if err != nil {
		logrus.Errorf("failed to post request: %v", err.Error())
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		logrus.Errorf("received non-OK status code: %d", resp.StatusCode)
		return
	}

	logrus.Debugf("DingTalk Message sent successfully.")
}
